package com.shyfu.dao;

import com.shyfu.entities.Book;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by Svitlana on 04-Apr-14.
 */
@Repository
public class BookDAOImpl implements BookDAO {

    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public void addBook(Book book) {
        sessionFactory.getCurrentSession().save(book);
    }

    @Override
    public void removeBook(Book book) {
        sessionFactory.getCurrentSession().delete(book);
    }

    @Override
    public void removeBook(long id) {
        Book book = getBook(id);
        if (book != null) {
            removeBook(book);
        }
    }

    @Override
    public List<Book> getAllBooks() {
        return sessionFactory.getCurrentSession().createQuery("from Book order by created").list();
    }

    @Override
    public Book getBook(long id) {
        Book book = (Book) sessionFactory.getCurrentSession().load(Book.class, id);
        System.out.println("dao book.title" + book.getUser());
        System.out.println("dao book = " + book);
        return book;
    }
}
